//
//  wareViewController.m
//  lmq
//
//  Created by 千翼网络科技 on 2017/1/10.
//  Copyright © 2017年 yuanxin. All rights reserved.
//

#import "wareViewController.h"
#import "UIView+Common.h"
#import "homeViewController.h"
#import "hotCollectionViewCell.h"
#import "goodsViewController.h"
#import "UIImageView+WebCache.h"
#import "MJRefresh.h"
#import "configddd.h"
#import <CoreLocation/CoreLocation.h>
#import "searchViewController.h"
#import <Masonry/Masonry.h>

@interface wareViewController ()<CLLocationManagerDelegate>{
    
//    CLLocationManager * _locationManager;
    NSString * currentCity; //当前城市
    CLGeocoder *_geocoder;
    
    int historyX;
}

@property(nonatomic,strong) CLLocationManager *locationManager;

@end

@implementation wareViewController

- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    hotCollectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        [self requestData];
        [hotCollectionView.mj_header endRefreshing];
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self locate];
    
    [self leftNavHide];
    [self setTitle:@"分类"];
    self.automaticallyAdjustsScrollViewInsets  = YES;
    [self requestData];
    
    [hotCollectionView.mj_header beginRefreshing];
    /*
    UIButton *leftButton=[[UIButton alloc]initWithFrame:CGRectMake(0, 0, screenScale(100), screenScale(34))];
    [leftButton addTarget:self action:@selector(leftNavItemClick) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *leftBarButton=[[UIBarButtonItem alloc]initWithCustomView:leftButton];
    self.navigationItem.leftBarButtonItem=leftBarButton;
    
    UIImageView *addressImageView=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, screenScale(34), screenScale(34))];
    addressImageView.image=[UIImage imageNamed:@"address"];
    [leftButton addSubview:addressImageView];
    
    addressLabel=[[UILabel alloc]init];
    addressLabel.text=@"";
    addressLabel.font = get4sFont(16);
    addressLabel.textColor=[UIColor whiteColor];
    [leftButton addSubview:addressLabel];
    [addressLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(addressImageView).with.offset(0);
        make.left.mas_equalTo(addressImageView).with.offset(screenScale(34));
        
        make.height.mas_equalTo(screenScale(34));
    }];
     */
    [self locate];
    
    UIButton *rightButton=[[UIButton alloc]initWithFrame:CGRectMake(0, 0, screenScale(34), screenScale(34))];
    [rightButton addTarget:self action:@selector(rightNavItemClick) forControlEvents:UIControlEventTouchUpInside];
    [rightButton setBackgroundImage:[UIImage imageNamed:@"serach"] forState:UIControlStateNormal];
    [rightButton setBackgroundImage:[UIImage imageNamed:@"serach"] forState:UIControlStateSelected];
    UIBarButtonItem *rightBarButton=[[UIBarButtonItem alloc]initWithCustomView:rightButton];
    self.navigationItem.rightBarButtonItem=rightBarButton;
    
    _topNaviV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, screenScale(68))];
    _topNaviV.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:_topNaviV];
    
    _scrollV = [[UIScrollView alloc] initWithFrame:CGRectMake(0, _topNaviV.bottom, DEF_SCREEN_WIDTH, DEF_SCREEN_HEIGHT-64-49-screenScale(68))];
    [_scrollV setPagingEnabled:YES];//开启分页，也就是不允许滑动到一半
    [_scrollV setShowsHorizontalScrollIndicator:NO];//设置水平方向的滚动条:
    [self.view addSubview:_scrollV];
    _scrollV.delegate = self;
    _scrollV.bounces=NO;
//    _scrollV.alwaysBounceVertical = YES;
//    _scrollV.alwaysBounceHorizontal = YES;
    _scrollV.backgroundColor=[ZJCModel colorWithString:@"f2f2f2"];
    [_scrollV.panGestureRecognizer addTarget:self action:@selector(scrollHandlePan:)];
    
    UIView *xView=[[UIView alloc]initWithFrame:CGRectMake(0, DEF_SCREEN_HEIGHT-49-64-(1), DEF_SCREEN_WIDTH, (1))];
    xView.backgroundColor=[UIColor grayColor];
    [self.view addSubview:xView];
}

- (void)requestData{
    
//    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[[UIApplication sharedApplication]keyWindow] animated:YES];
//    hud.tag = 500;
//    //提示文本
//    hud.labelText = @"正在加载...";
//    //是否有遮罩
//    hud.dimBackground = YES;
    
    [[MNetworkHandler sharedInstance]conURL:Category_Hot
                                networkType:NetWorkPOST
                                     params:nil
                                   delegate:nil
                                    showHUD:NO
                               successBlock:^(id returnData) {
                                   if ([[returnData objectForKey:@"code"]intValue]==1) {
                                       
                                       myArr = [returnData objectForKey:@"data"];
                                       NSLog(@"==\n\n\n==myArr====%@",myArr);
                                       [self createTwo];
                                       
//                                       [hud removeFromSuperview];
                                   }
                                   else if ([[returnData objectForKey:@"code"]intValue]==-1){
                                       
                                       [PublicFunction showAlert:nil message:[returnData objectForKey:@"msg"] duration:5.0f];
                                       
                                   }
                               } failureBlock:^(NSError *error) {
                                   
//                                   [hud removeFromSuperview];
                                   NSLog(@"%@",error);
                                   [PublicFunction showAlert:nil message:@"没有连接网络" duration:10.0f];
                                   sleep(2);
                                   [self requestData];
                               }];
}

#pragma mark ---------- init ----------

- (void)createTwo{
    
//    上边ScrollView
    
    //    NSArray *arT = @[@"热销品牌", @"测试2", @"测试3", @"测试4", @"测试5"];
    NSMutableArray *nArr=[[NSMutableArray alloc]init];
    for (int i = 0; i < myArr.count; i++) {
        NSString *nStr=[myArr[i] objectForKey:@"name"];
        [nArr addObject:nStr];
    }
    NSArray *arT=[nArr copy];
    _navScrollV = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, screenScale(68))];
    [_navScrollV setShowsHorizontalScrollIndicator:NO];
    [_topNaviV addSubview:_navScrollV];
    
    for (int i = 0; i < [arT count]; i++){
        
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn setFrame:CGRectMake(screenScale(115) * i, screenScale(0), screenScale(115), screenScale(68))];
        btn.titleLabel.font = get4sFont(13);
        [btn setTitleColor:[ZJCModel colorWithString:@"222222"] forState:UIControlStateSelected];
        [btn setTitleColor:[ZJCModel colorWithString:@"666666"] forState:UIControlStateNormal];
        [btn setTitle:[arT objectAtIndex:i] forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        btn.tag = i + 1;
        [btn addTarget:self action:@selector(actionbtn:) forControlEvents:UIControlEventTouchUpInside];
        [_navScrollV addSubview:btn];
    }
    [_navScrollV setContentSize:CGSizeMake(screenScale(115) * [arT count], screenScale(68))];
    
    // 黑线
    _navBgV = [[UIView alloc] initWithFrame:CGRectMake(screenScale(8), screenScale(65) ,screenScale(100), screenScale(3))];
    [_navBgV setBackgroundColor:[ZJCModel colorWithString:@"222222"]];
    [_navScrollV addSubview:_navBgV];
    
    // 灰线
    UIView *gView=[[UIView alloc]initWithFrame:CGRectMake(0, screenScale(67), screenScale(115) * [arT count], screenScale(1))];
    gView.backgroundColor=[ZJCModel colorWithString:@"f2f2f2"];
    [_navScrollV addSubview:gView];
    
//    下边scrollView
    
    [_scrollV setContentSize:CGSizeMake(_scrollV.frame.size.width * [arT count], _scrollV.frame.size.height)];
    
    myHotCollectionViewArr = [[NSMutableArray alloc]init];
    for (int i = 0; i < [arT count]; i++){
        
        UICollectionViewFlowLayout *layout=[[UICollectionViewFlowLayout alloc]init];
        layout.minimumLineSpacing = screenScale(20);//上下行cell的间距
        layout.minimumInteritemSpacing = screenScale(20);
//        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        
        hotView=[[UIView alloc]initWithFrame:CGRectMake(i * DEF_SCREEN_WIDTH, 0, DEF_SCREEN_WIDTH, DEF_SCREEN_HEIGHT-49-64-screenScale(1))];//75+400+8
        hotView.backgroundColor=[UIColor whiteColor];
        [_scrollV addSubview:hotView];
        
        hotCollectionView=[[UICollectionView alloc]initWithFrame:CGRectMake((DEF_SCREEN_WIDTH-2*(screenScale(288)))/3 , 0, DEF_SCREEN_WIDTH - screenScale(40) , DEF_SCREEN_HEIGHT-49-64-screenScale(80)) collectionViewLayout:layout];
        hotCollectionView.delegate=self;
        hotCollectionView.dataSource=self;
//        hotCollectionView.alwaysBounceVertical = YES;
        hotCollectionView.showsVerticalScrollIndicator = NO;
        hotCollectionView.backgroundColor= [UIColor whiteColor];
        [hotCollectionView registerClass:[hotCollectionViewCell class] forCellWithReuseIdentifier:@"hotCollectionViewCell"];
        [hotView addSubview:hotCollectionView];
        
        [myHotCollectionViewArr addObject:hotCollectionView];
    }
    NSLog(@"%lu",(unsigned long)[arT count]);
}

#pragma mark ------------------------------------------------ action

- (void)actionbtn:(UIButton *)btn
{
    wareIndex = btn.tag - 1.0;
    
    [myHotCollectionViewArr[wareIndex] reloadData];
    [_scrollV scrollRectToVisible:CGRectMake(_scrollV.frame.size.width * (btn.tag - 1), _scrollV.frame.origin.y, _scrollV.frame.size.width, _scrollV.frame.size.height) animated:YES];
    
    float xx = _scrollV.frame.size.width * (btn.tag - 1) * (screenScale(115) / self.view.frame.size.width) - screenScale(115);
    [_navScrollV scrollRectToVisible:CGRectMake(xx, 0, _navScrollV.frame.size.width, _navScrollV.frame.size.height) animated:YES];
}

// 两边显示左右页面
-(void)scrollHandlePan:(UIPanGestureRecognizer*) panParam
{
    BOOL isPaning = NO;
    //NSLog(@"fff%f",_scrollV.contentOffset.x);
    if(_scrollV.contentOffset.x <= 0)
    {
        isPaning = YES;
        //[self.sideMenuViewController presentLeftMenuViewController];
    }
    else if(_scrollV.contentOffset.x >= (_scrollV.contentSize.width - _scrollV.frame.size.width))
    {
        isPaning = YES;
        //[self.sideMenuViewController presentRightMenuViewController];
    }
    if(isPaning)
    {
        [self.sideMenuViewController panGestureRecognizedFrom:panParam];
    }
}

// 改变黑线线位置
- (void)changeView:(float)x
{
    float xx = x * (screenScale(115) / self.view.frame.size.width);
    
    [_navBgV setFrame:CGRectMake(xx+screenScale(8), _navBgV.frame.origin.y, _navBgV.frame.size.width, _navBgV.frame.size.height)];
}
#pragma mark - UIScrollViewDelegate

// 开始拖拽视图
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    
    //scrollView.contentOffset.x;
    NSLog(@"scrollViewWillBeginDragging");
    
    historyX = scrollView.contentOffset.x;
}

// 只要滚动了就会触发
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    // 横向滑动时改变黑线线
    
    if (scrollView.contentOffset.x < historyX) {
        
        [self changeView:scrollView.contentOffset.x];
        
    } else if (scrollView.contentOffset.x > historyX) {
        
        [self changeView:scrollView.contentOffset.x];
        
    }
}

//完成拖拽
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    
    if (scrollView.contentOffset.x < historyX) {
        
        wareIndex= scrollView.contentOffset.x/DEF_SCREEN_WIDTH;
        
        [myHotCollectionViewArr[wareIndex] reloadData];
        // 滚动到红线对应菜单
        float xx = scrollView.contentOffset.x * ((80) / self.view.frame.size.width) - (80);
        [_navScrollV scrollRectToVisible:CGRectMake(xx, 0, _navScrollV.frame.size.width, _navScrollV.frame.size.height) animated:YES];
        
    } else if (scrollView.contentOffset.x > historyX) {
        
        wareIndex= scrollView.contentOffset.x/DEF_SCREEN_WIDTH;
        
        [myHotCollectionViewArr[wareIndex] reloadData];
        // 滚动到红线对应菜单
        float xx = scrollView.contentOffset.x * ((80) / self.view.frame.size.width) - (80);
        [_navScrollV scrollRectToVisible:CGRectMake(xx, 0, _navScrollV.frame.size.width, _navScrollV.frame.size.height) animated:YES];
        
    }
}


#pragma mark - 点击左导航

-(void)leftNavItemClick{
    
    [self locate];
    NSLog(@"点击定位");
}

#pragma mark - 点击右导航

-(void)rightNavItemClick{
    
    NSLog(@"搜索");
    
    searchViewController *searchVC = [[searchViewController alloc]init];
    searchVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:searchVC animated:YES];
}

#pragma mark - CollectionView ---------------------------------------

//section 的个数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    
    return 1;
}

//cell的个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    NSDictionary *dict=myArr[wareIndex];
    NSArray *myArr1=[dict objectForKey:@"son"];
    return myArr1.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *identify = @"hotCollectionViewCell";
    hotCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identify forIndexPath:indexPath];
    
//    cell.myCollectionView=categoryCollectionView;
//    cell.homeVC=self;
    
    NSDictionary *dict = myArr[wareIndex];
    NSArray *myArr1 = [dict objectForKey:@"son"];
    
    NSDictionary *dict1 = myArr1[indexPath.row];
    NSString *urlWare = [dict1 objectForKey:@"casepic"];
    NSString *urlN = manage(AP_HOST, urlWare);
    
//    http://192.168.1.88//uploads/20170113\065547f4b7680a88d88d63e7165fe500.png
    NSString *strUrl = [urlN stringByReplacingOccurrencesOfString:@"\\" withString:@"/"];
    NSURL *urlW = [NSURL URLWithString:strUrl];
    [cell.imageshow sd_setImageWithURL:urlW placeholderImage:[UIImage imageNamed:@"niunai"]];
    
    return cell;
}

-(void)itemSelect:(NSIndexPath*)index{

}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"%@",@(indexPath.row).description);
    
//    nsdict  dict = [myArr[i] objectForKey:@"son"]
//    nsstring str=[dict objectForKey:@"pid"];
    
    goodsViewController *goodsVC=[[goodsViewController alloc]init];

    NSArray *aArr = [myArr[wareIndex] objectForKey:@"son"];
    
    NSLog(@"\n\n\nwareIndex=%d",wareIndex);
    
    NSDictionary *aDict = aArr[indexPath.row];
    goodsVC.myStr = [aDict objectForKey:@"id"];
    goodsVC.tittleStr = [myArr[wareIndex] objectForKey:@"name"];
    
    [self.navigationController pushViewController:goodsVC animated:YES];
    
}

#pragma mark -- UICollectionViewDelegate
//设置每个 UICollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(screenScale(288), screenScale(169));
}
//定义每个UICollectionView 的间距
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{

    return UIEdgeInsetsMake(screenScale(20), 0, 0,0);//上、左、下、右
}

//定义每个UICollectionView 的横向间距
-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 0;
}


-(BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}

#pragma mark --------- 定位 ----------

- (void)locate {
    
    //定位管理器
    _locationManager=[[CLLocationManager alloc]init];
    //    _locationManager.allowsBackgroundLocationUpdates  = YES;
    //设置代理
    _locationManager.delegate = self;
    //设置定位精度
    _locationManager.desiredAccuracy=kCLLocationAccuracyBest;
    //定位频率,每隔多少米定位一次
    CLLocationDistance distance=10.0;//十米定位一次
    _locationManager.distanceFilter=distance;
    //启动跟踪定位
    [_locationManager startUpdatingLocation];
    
    _geocoder=[[CLGeocoder alloc]init];
    //    [self getCoordinateByAddress:@"北京"];
    //    [self getAddressByLatitude:39.54 longitude:116.28];
    
    if (![CLLocationManager locationServicesEnabled]) {
        NSLog(@"定位服务当前可能尚未打开，请设置打开！");
        return;
    }
    
    if ([[[UIDevice currentDevice]systemVersion]floatValue] >= 8.0) {
        
        [self.locationManager requestAlwaysAuthorization];
        [_locationManager requestWhenInUseAuthorization];
    }
    
    //如果没有授权则请求用户授权
    if ([CLLocationManager authorizationStatus]==kCLAuthorizationStatusNotDetermined){
        
        [_locationManager requestWhenInUseAuthorization];
        
    }else if([CLLocationManager authorizationStatus]==kCLAuthorizationStatusAuthorizedWhenInUse){
        
        //设置代理
        _locationManager.delegate = self;
        //设置定位精度
        _locationManager.desiredAccuracy=kCLLocationAccuracyBest;
        //定位频率,每隔多少米定位一次
        CLLocationDistance distance=10.0;//十米定位一次
        _locationManager.distanceFilter=distance;
        //启动跟踪定位
        [_locationManager startUpdatingLocation];
    }
    
}

#pragma mark CoreLocation delegate

//定位失败则执行此代理方法
//定位失败弹出提示框,点击"打开定位"按钮,会打开系统的设置,提示打开定位服务
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    
    UIAlertController * alertVC = [UIAlertController alertControllerWithTitle:@"允许\"定位\"提示" message:@"请在设置中打开定位" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction * ok = [UIAlertAction actionWithTitle:@"打开定位" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //打开定位设置
        NSURL *settingsURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        [[UIApplication sharedApplication] openURL:settingsURL];
    }];
    UIAlertAction * cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alertVC addAction:cancel];
    [alertVC addAction:ok];
    [self presentViewController:alertVC animated:YES completion:nil];
    
}
//定位成功
#pragma mark - CoreLocation 代理
#pragma mark 跟踪定位代理方法，每次位置发生变化即会执行（只要定位到相应位置）

//可以通过模拟器设置一个虚拟位置，否则在模拟器中无法调用此方法
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
    
    CLLocation *location=[locations firstObject];//取出第一个位置
    CLLocationCoordinate2D coordinate=location.coordinate;//位置坐标
    NSLog(@"经度：%f,纬度：%f,海拔：%f,航向：%f,行走速度：%f",coordinate.longitude,coordinate.latitude,location.altitude,location.course,location.speed);
    //如果不需要实时定位，使用完即使关闭定位服务
    [_locationManager stopUpdatingLocation];
    
    //[self getAddressByLatitude:coordinate.latitude longitude:coordinate.longitude];
    
    // 获取当前所在的城市名
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    //根据经纬度反向地理编译出地址信息
    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *array, NSError *error)
     {
         if (array.count > 0)
         {
             CLPlacemark *placemark = [array objectAtIndex:0];
             
             //将获得的所有信息显示到label上
             //self.location.text = placemark.name;
             //获取城市
             NSString *city = placemark.locality;
             if (!city) {
                 //四大直辖市的城市信息无法通过locality获得，只能通过获取省份的方法来获得（如果city为空，则可知为直辖市）
                 city = placemark.administrativeArea;
             }
             NSLog(@"city = %@", city);
             
//             addressLabel.text = placemark.administrativeArea;
//             addressLabel.text = city;
             
             NSDictionary *dict =[[NSDictionary alloc]initWithObjectsAndKeys:@"yes",@"select",city,@"location", nil];
             NSNotification *notification =[NSNotification notificationWithName:@"location" object:nil userInfo:dict];
             [[NSNotificationCenter defaultCenter] postNotification:notification];
             
         }
         else if (error == nil && [array count] == 0)
         {
             NSLog(@"No results were returned.");
         }
         else if (error != nil)
         {
             NSLog(@"An error occurred = %@", error);
         }
     }];
}

@end
